package top.kaoshanji.p1ch03a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.u1constant.FileConstant;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 代码清单 p1ch03a-11：使用字节缓冲区进行文件复制的示例
 * 运行之后会生成 深入理解Java7：核心技术与最佳实践-成富-随书源码-dest.7z 文件，看过之后就删掉
 * author kaoshanji
 * ^_^
 * create time 2025/1/6 19:58
 */
public class ByteBufferExample05 {

    private static final Logger logger = LogManager.getLogger(ByteBufferExample05.class);

    public static void main(String[] args) {
        logger.info("...代码清单 p1ch03a-11：使用字节缓冲区进行文件复制的示例...");

        ByteBuffer buffer = ByteBuffer.allocateDirect(32 * 1024); // 直接缓冲区
        try (FileChannel src = FileChannel.open(Paths.get(FileConstant.SRC_COPY_FILE), StandardOpenOption.READ);
             FileChannel dest = FileChannel.open(Paths.get(FileConstant.DEST_COPY_FILE), StandardOpenOption.WRITE, StandardOpenOption.CREATE)){

            while (src.read(buffer) > 0 || buffer.position() != 0) {
                buffer.flip();
                dest.write(buffer);
                buffer.compact();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}
